import React from 'react';
import { Row, Col, Form, InputNumber, Input, Button, Table, Select, Modal, message } from 'antd';
import { connect } from 'dva';
const R = require('ramda');

const FormItem = Form.Item;
const productAddTempIdPrefix = 'productAddTempIdPrefix_';
export default connect(({ orderAgent }) => ({ orderAgent }))(
  Form.create({ wrappedComponentRef: true })(
    class ChooseProduct extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          open: false,
          tempSelectProductKeys: [],
          tempSelectProduct: [],
        };
      }

      productAddTempId = 0;

      handleCancel = () => {
        const { form } = this.props;
        form.setFieldsValue({ productName: '', productModel: '' });
        this.setState({ open: false, tempSelectProductKeys: [], tempSelectProduct: [] });
      };

      handleOpen = () => {
        this.setState({ open: true });
      };

      handleConform = () => {
        //判断所选产品的币种是否与所选币种一致，如果不一致则不允许选择。
        let flag = true;
        let messageInfo = '';

        R.map(row => {
          if (R.isNil(row.zzrate) || R.isNil(row.taxrate)) {
            flag = false;
            messageInfo = '产品的增值税率或者退税率为空，请维护基础数据!';
          }
        }, this.state.tempSelectProduct);

        if (flag) {
          let parseList = [];
          R.map(row => {
            let parseProduct = {};
            parseProduct.id = productAddTempIdPrefix + this.productAddTempId;
            this.productAddTempId++; //临时的唯一id
            parseProduct.key = parseProduct.id; //加上key 不然会抛错
            parseProduct.productorderid = this.props.orderId; //订单id
            parseProduct.productid = row.id; //产品id
            parseProduct.productname = row.name; //品名
            parseProduct.productmodel = row.model; // 型号
            parseProduct.productbranch = row.branch; //品牌
            parseProduct.productbranchtype = row.branchtype; //品牌类型
            parseProduct.productbranchname = row.branchtypename; //品牌类型
            parseProduct.productunit = row.unit; //单位
            parseProduct.productprice = row.price; //单价
            parseProduct.productoriginalprice = row.price; //原始单价
            parseProduct.productcurrency = row.currency; //币种
            parseProduct.singleweight = row.weight; //单净重
            parseProduct.productsize = row.size; //规格
            parseProduct.productdeclarelements = row.declarelements; //申报要素
            parseProduct.producthscode = row.hscode; // hscode
            parseProduct.taxrate = row.taxrate; //退税率
            parseProduct.zzrate = row.zzrate; //增值税率
            parseProduct.xfrate = row.xfrate; //消费税率
            parseProduct.iseffecthscode = row.iseffecthscode; //规格是否影响海关编码
            parseProduct.drawbackcode = row.drawbackcode; //税局hscode
            parseProduct.drawerid = ''; //开票人id
            parseProduct.supercondition = row.supercondition; //监管条件
            parseList = R.concat(parseList, [parseProduct]);
          }, this.state.tempSelectProduct);

          if (this.props.handleAddProducts) {
            this.props.handleAddProducts(parseList);
          }
          this.handleCancel();
        } else {
          message.error(messageInfo);
          return;
        }
      };

      handleProductSearch = () => {
        const {
          form: { getFieldsValue },
          dispatch,
          userInfo,
          orderAgent,
        } = this.props;

        let values = getFieldsValue();
        let newPage = orderAgent.productPage;
        newPage.page = 1;
        dispatch({
          type: 'orderAgent/queryProductList',
          payload: {
            ...values,
            cstId: userInfo.id,
            page: newPage.page,
            size: newPage.size,
          },
        });
      };

      handleChangeProductSelection = (selectedRowKeys, selectedRows) => {
        this.setState({
          tempSelectProductKeys: selectedRowKeys,
          tempSelectProduct: selectedRows,
        });
      };

      columns = [
        { title: '海关HSCode', dataIndex: 'hscode', key: 'hscode' },
        { title: '税局HSCode', dataIndex: 'drawbackcode', key: 'drawbackcode' },
        { title: '品名', dataIndex: 'name', key: 'name' },
        { title: '型号', dataIndex: 'model', key: 'model' },
        { title: '品牌类型', dataIndex: 'branchtypename', key: 'branchtypename' },
        { title: '品牌', dataIndex: 'branch', key: 'branch' },
        { title: '单价', dataIndex: 'price', key: 'price' },
        { title: '申报要素', dataIndex: 'declarelements', key: 'declarelements' },
        { title: '币种', dataIndex: 'currency', key: 'currency' },
        { title: '规格', dataIndex: 'size', key: 'size' },
        { title: '退税率(%)', dataIndex: 'taxrate', key: 'taxrate' },
        { title: '增值税率(%)', dataIndex: 'zzrate', key: 'zzrate' },
        { title: '净重(kg)', dataIndex: 'weight', key: 'weight' },
      ];

      render() {
        const {
          orderAgent: { productPage, productList },
          form: { getFieldsValue, getFieldDecorator },
          dispatch,
          userInfo,
        } = this.props;
        let values = getFieldsValue();

        let pagination = {
          showTotal: total => `共 ${total} 条数据`,
          current: productPage.page,
          pageSize: productPage.size,
          total: productPage.totalRow,
          showSizeChanger: true,
          onShowSizeChange: (current, size) => {
            let newPage = productPage;
            newPage.size = size;
            newPage.page = 1;
            dispatch({
              type: 'orderAgent/queryProductList',
              payload: {
                ...values,
                cstId: userInfo.id,
                page: newPage.page,
                size: newPage.size,
              },
            });
          },
          onChange: (pageNumber, pageSize) => {
            this.setState({
              tempSelectMsgKeys: [],
              tempSelectMsg: [],
            });
            let newPage = productPage;
            newPage.page = pageNumber;
            dispatch({
              type: 'orderAgent/queryProductList',
              payload: {
                ...values,
                cstId: userInfo.id,
                page: newPage.page,
                size: newPage.size,
              },
            });
          },
        };

        const formItemLayout = { labelCol: { span: 9 }, wrapperCol: { span: 15 } };

        let rowSelection = {
          onChange: (selectedRowKeys, selectedRows) => {
            this.setState({
              tempSelectProductKeys: selectedRowKeys,
              tempSelectProduct: selectedRows,
            });
          },
          selectedRowKeys: this.state.tempSelectProductKeys,
        };

        return (
          <Modal
            maskClosable={false}
            visible={this.state.open}
            title={'添加产品'}
            width={1400}
            wrapClassName="vertical-center-modal"
            onCancel={this.handleCancel.bind(this)}
            onOk={this.handleConform.bind(this)}
          >
            <Form layout="inline" style={{ marginBottom: 15 }}>
              <FormItem {...formItemLayout} label="产品名称" hasFeedback>
                {getFieldDecorator('productName')(<Input maxLength="30" />)}
              </FormItem>

              <FormItem {...formItemLayout} label="产品型号" hasFeedback>
                {getFieldDecorator('productModel')(<Input maxLength="30" />)}
              </FormItem>

              <Button
                type="primary"
                icon="search"
                style={{ marginRight: 5 }}
                onClick={this.handleProductSearch.bind(this)}
              >
                查询
              </Button>
            </Form>

            <Table
              rowKey={record => record.id}
              dataSource={productList}
              rowSelection={rowSelection}
              columns={this.columns}
              bordered={false}
              size={'middle'}
              pagination={pagination}
              scroll={{ x: 1400 }}
            />
          </Modal>
        );
      }
    },
  ),
);
